package com.dream.auth.controller;

import com.alibaba.fastjson.JSONObject;
import com.dream.auth.config.DreamAuthConfig;
import com.dream.auth.domain.models.LoginBody;
import com.dream.auth.service.SysLoginService;
import com.dream.core.constant.Constants;
import com.dream.core.core.domain.AjaxResult;
import com.dream.web.utils.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Controller
public class LoginController {
    @Autowired
    private SysLoginService loginService;
    @Autowired
    DreamAuthConfig  dreamAuthConfig;
    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/login")
    public String login(Model model, HttpServletRequest request) {
        model.addAttribute("loginProcessUrl",request.getContextPath()+"/login");
        String returnUrl = request.getHeader("Referer");
        model.addAttribute("returnUrl",returnUrl);
        return "login";
    }
    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login2")
    @ResponseBody
    public AjaxResult login2(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }
   /* @PostMapping("/login")
    @ResponseBody
    public AjaxResult login(String username,String password,String code,String uuid) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(username, password,code,uuid);
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }*/
   @PostMapping("/login")
   @ResponseBody
   public AjaxResult login(String username,String password,String code,String uuid ,@RequestHeader HttpHeaders httpHeaders) {
       AjaxResult ajax = AjaxResult.success();
       Map result = getToken(username, password, null,httpHeaders);
       Object accessToken="";
       if (result.containsKey("value")) {
           accessToken=result.get("value");
       }
       ajax.put(Constants.TOKEN, accessToken);
       return ajax;
   }
    public JSONObject getToken(String userName, String password, String type, HttpHeaders headers) {
        String url = WebUtils.getServerUrl(WebUtils.getHttpServletRequest()) + "/oauth/token";
        // 使用oauth2密码模式登录.
        MultiValueMap<String, Object> postParameters = new LinkedMultiValueMap<>();
        postParameters.add("username", userName);
        postParameters.add("password", password);
        postParameters.add("client_id", dreamAuthConfig.getClientId());
        postParameters.add("client_secret", dreamAuthConfig.getClientSecret());
        postParameters.add("grant_type", "password");
        // 添加参数区分,第三方登录
        postParameters.add("login_type", type);
        // 使用客户端的请求头,发起请求
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        // 强制移除 原来的请求头,防止token失效
        headers.remove(HttpHeaders.AUTHORIZATION);
        HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity(postParameters, headers);
        JSONObject result = restTemplate.postForObject(url, request, JSONObject.class);
        return result;
    }
}
